<?php

namespace sws\route;

class RouteGroup
{

    /**
     * 上一层路由分组
     * @var RouteGroup
     */
    private $routeGroup;

    /**
     * 当前路由分组名
     * @var string
     */
    private $groupName;

    /**
     * 当前分组上的中间件
     * @var array
     */
    public $middleware = [];

    /**
     * @param null   $routeGroup
     * @param string $groupName
     */
    public function __construct($routeGroup = null, string $groupName = '')
    {
        $this->routeGroup = $routeGroup;
        $this->groupName = $groupName;
    }

    /**
     * 分组添加中间件
     * @param $middleware
     * @param ...$params
     * @return $this
     */
    public function middleware($middleware, ...$params): RouteGroup
    {
        if (is_array($middleware)) {
            $this->middleware = array_merge($this->middleware, $middleware);
        } else {
            array_unshift($params, $middleware);
            $this->middleware = array_merge($this->middleware, $params);
        }
        return $this;
    }

    /**
     * 添加路由
     * @param        $method
     * @param string $route
     * @param        $handler
     * @return RouteRule
     */
    public function addRoute($method, string $route, $handler): RouteRule
    {
        return (new RouteRule($method, $route, $handler, $this));
    }

    /**
     * 获取分组名
     * @return string
     */
    public function getGroupName(): string
    {
        $superiorGroupName = '';
        if ($this->routeGroup instanceof RouteGroup) {
            $superiorGroupName = $this->routeGroup->getGroupName();
        }
        return $superiorGroupName . $this->groupName;
    }

    /**
     * 获取分组中间件
     * @return array
     */
    public function getMiddleware(): array
    {
        $middleware = $this->middleware;
        if ($this->routeGroup instanceof RouteGroup) {
            $middleware =  array_merge($this->routeGroup->getMiddleware(),$middleware);
        }
        return $middleware;
    }


}